package com.mxm.mirai.web;

import com.mxm.mirai.dao.Botgroups;
import com.mxm.mirai.dao.User;
import com.mxm.mirai.jwt.JWTUtil;
import com.mxm.mirai.service.BotconfigService;
import com.mxm.mirai.service.BotgroupsService;
import com.mxm.mirai.service.UserService;
import com.mxm.mirai.tools.BotLogin;
import com.mxm.mirai.config.MXM_config;
import com.mxm.mirai.dao.Table_Json;
import com.mxm.mirai.tools.BotTools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.contact.ContactList;
import net.mamoe.mirai.contact.Friend;
import net.mamoe.mirai.contact.Group;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@Api(value = "Bot 操作类")
public class BotWeb {
    private static Map<String,Object> datastate= new HashMap<>();
    private static BotTools botTools = new BotTools();
    private static User user=null;
    @Autowired
    BotgroupsService botgroupsService;
    @Autowired
    BotconfigService botconfigService;
    @Autowired
    UserService userService;

    @PostMapping("/AddBot")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    @ApiOperation(value = "添加登录bot", notes = "Bot登录--拦截")
    public Map AddBot(String qq, String passwrod, HttpServletRequest request){
        if("".equals(qq) || "".equals(passwrod) || qq==null || passwrod ==null){
            datastate.put("msg","QQ/密码 不能为空！");
            return datastate;
        }
//        System.out.println("token:"+request.getHeader("token"));
        String name = JWTUtil.getUsername(request.getHeader("token"));
        //查询已用配额
        List<Botgroups> botgroups = botgroupsService.QueryBotGroupsByMaster(name);
        System.out.println("botgroups:"+botgroups.toString());
        Integer js = 0;
        if(botgroups != null){
            for (Botgroups group:botgroups) {
                if(botTools.inBotOnline(group.getQq())){
                    js+=1;
                }
            }
        }
        //查询可用配额
        user = userService.getUserByUsername(name);
        //可用配额-已用配额=<0
        System.out.println("可用:"+user.getQuota()+"____已用:"+js);
        if(user.getQuota()-js<1){
            datastate.put("msg","代挂额已不足");
            return datastate;
        }
        if(user.getDuedate().getTime() < new Date().getTime()){
            datastate.put("msg","到期提醒，请续费使用！");
            return datastate;
        }
        datastate.put("msg",new BotLogin().Run(qq,passwrod));
        //成功登录保存信息置botqup
        botgroupsService.AbbBotGroupsQQByMaster(qq,name);
        return datastate;
    }
    @GetMapping("/LogOut/{qq}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    @ApiOperation(value = "Bot在线状态", notes = "在线状态--拦截")
    public String LogOut(@PathVariable(name="qq") String qq){
        System.out.println("退出QQ："+qq);
        try {
            Bot.getInstance(new Long(qq)).close(null);
        }catch (Exception e){
        }
        if (MXM_config.bottools.inBotOnline(qq)){
            System.out.println("还在线");
            return "0";
        }else {
            System.out.println("己下线");
            return "1";
        }
    }
    @GetMapping("/getBotConfigState/{qq}")
    @ApiOperation(value = "Q群配置状态获取", notes = "状态获取--拦截")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public Map getBotConfigState(@PathVariable(name="qq") String qq){
        datastate = new HashMap<>();
        datastate.put("messageformat_on_off","1".equals(botconfigService.QueryBotConfigState(qq,"messageformat"))?true:false);
        return datastate;
    }
    /**
     * Q群功能配置管理
     * @param qq
     */
    @PostMapping("/UpdateBotConfigState")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    @ApiOperation(value = "Q群功能配置管理", notes = "功能配置管理--拦截")
    public String UpdateBotConfigState(String qq,String task,boolean state){
        String index = state?"1":"0";
        if(botconfigService.UpdateBotConfigQQ(qq,task,index,null)){
            return index;
        }else {
            return index;
        }
    }
    /**
     * 获取Bot例表
     */
    @GetMapping("/getBots")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    @ApiOperation(value = "获取Bot例表", notes = "获取Bot例表--拦截")
    public Map getBots(HttpServletRequest request){
        datastate = new HashMap();
        List list = new LinkedList();
        Map map = null;
        try {
            for (Bot bot:Bot.getBotInstances()) {
                if(QueryBotByMaster(bot.getId(),request)){
                map = new HashMap();
                map.put("qq",bot.getId());
                map.put("name",bot.getNick());
                list.add(map);
                }
            }
            datastate.put("list",list);
        }catch (Exception e){
            datastate.put("msg","0");
        }
        return datastate;
    }
    /**
     * 获取Bot例表
     */
    @GetMapping("/getAdmin_Bots")
    @RequiresRoles(logical = Logical.OR, value = {"admin"})
    @ApiOperation(value = "获取Bot例表", notes = "获取Bot例表--拦截")
    public Table_Json getAdmin_Bots(){
        List list = new LinkedList();
        Integer index=0;
        Map map = null;
        try {
            for (Bot bot:Bot.getBotInstances()) {
                String username = botgroupsService.QueryBotGroupsQQByMaster(bot.getId());
                map = new HashMap();
                map.put("id",index);//从0开始
                map.put("bot",bot.getId());
                map.put("user","".equals(username)?"获取失败":username);
                list.add(map);
                index+=1;
            }
        }catch (Exception e){
            return new Table_Json(404,"获取失败",null,null);
        }
        return new Table_Json(0,null,new Long(index),list);
    }
    /**
     * 判断主人的Bot是否存在即在线
     * @param bot
     * @param request
     * @return
     */
    public boolean QueryBotByMaster(Long bot,HttpServletRequest request){
        String name = JWTUtil.getUsername(request.getHeader("token"));
        //查询已用配额
        List<Botgroups> botgroups = botgroupsService.QueryBotGroupsByMaster(name);
        if(botgroups != null){
            for (Botgroups group:botgroups) {
                if(botTools.inBotOnline(group.getQq()) && group.getQq().equals(String.valueOf(bot))){
                    return true;
                }
            }
        }
        return false;
    }
    @GetMapping("/getBotState/{qq}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    @ApiOperation(value = "获取Bot状态", notes = "获取Bot状态--拦截")
    public Map getBotState(@PathVariable(name="qq") String qq){
        Map map = new HashMap();
        try {
            Bot bot = Bot.getInstance(new Long(qq));
            map.put("qq",bot.getId());
            map.put("name",bot.getNick());
            map.put("friends",bot.getFriends().size());
            map.put("groups",bot.getGroups().size());
        }catch (Exception e){
            map.put("msg","获取失败");
        }
        return map;
    }

    @GetMapping("/BotDropOut/{qq}/{group}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    @ApiOperation(value = "退出Q群", notes = "退出Q群--拦截")
    public String BotDropOut(@PathVariable(name="qq") String qq,@PathVariable(name="group") String group){
        if(Bot.getInstance(new Long(qq)).getGroup(new Long(group)).quit()){
            return "成功退出";
        }else {
            return "已经退出";
        }
    }

    @GetMapping("/getFriends/{qq}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    @ApiOperation(value = "获取好友例表", notes = "获取好友例表--拦截")
    public Table_Json getFriends(@PathVariable(name="qq") String qq){
        if("".equals(qq) || qq==null)return new Table_Json(404,"QQ不能为空",null,null);
        if(!MXM_config.bottools.inBotOnline(qq))return new Table_Json(404,"QQ不存在",null,null);
        List list =  new LinkedList();
        Map map = null;
        ContactList<Friend> fri = Bot.getInstance(new Long(qq)).getFriends();
        for (Friend friend:fri) {
            map = new HashMap();
            map.put("qq",friend.getId());
            map.put("imgurl",friend.getAvatarUrl().replace("s=640","s=100"));
            map.put("name",friend.getNick());
            list.add(map);
        }
        return new Table_Json(0,null,new Long(fri.size()),list);
    }
    public Map GroupData(String qq,String group,String name,String value){
        Map map = new HashMap();
        map.put("name",name);
        map.put("value",value);
        map.put("group",group);
        if("1".equals(botgroupsService.QueryBotGroupsState(qq,String.valueOf(group),value))){
            map.put("selected",true);
        }else {
            map.put("selected",false);
        }
        return map;
    }

    /**
     * 获取群例表
     * @param qq
     */
    @GetMapping("/getGroups/{qq}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    @ApiOperation(value = "获取群例表", notes = "获取群例表--拦截")
    public Table_Json getGroups(@PathVariable(name="qq") String qq){
        if("".equals(qq) || qq==null)return new Table_Json(404,"QQ不能为空",null,null);
        if(!MXM_config.bottools.inBotOnline(qq))return new Table_Json(404,"QQ不存在",null,null);
        List list =  new LinkedList();
        Map map = null;
        List lista =  null;
        ContactList<Group> groups =Bot.getInstance(new Long(qq)).getGroups();
        for (Group group:groups) {
            map = new HashMap();
            lista = new LinkedList();
            lista.add(GroupData(qq,String.valueOf(group.getId()),"随机二次元图片","AcgRandomImg"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"bilibil监控","bilibilMonitor"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"微博热搜监控","WeiboMonitor"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"写诗","WritingPoems"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"cmd/ping","cmd_ping"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"复读(text,xml,json)","reread"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"二次元图片","AcgImg"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"智能抠图","SmartMatting"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"识图文字","ocrtext"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"卡牌生成","CreateCards"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"视频搜索","BotVideo"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"网易点歌","BotMusic163"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"百度搜索","BotBaiDu"));
            lista.add(GroupData(qq,String.valueOf(group.getId()),"戳一戳","Apoke"));


            map.put("group_data",lista);
            map.put("group_id",group.getId());//群号
            map.put("group_name",group.getName());//群名
            map.put("group_avatarUrl",group.getAvatarUrl());//群头像
            map.put("group_admin",group.getOwner().getNick());//群主名片名
            map.put("group_botMuteRemaining",group.getBotMuteRemaining());//机器人被禁言还剩余多少秒
            map.put("group_EntranceAnnouncement",group.getSettings().getEntranceAnnouncement());//入群公告
            switch (group.getBotPermission().getLevel()) {
                case 1://管理员
                    map.put("group_BotPermission","管理员");//在这个群里的权限
                    break; //可选
                case 2://群主
                    map.put("group_BotPermission","群主");//在这个群里的权限
                    break; //可选
                default: //一般群成员
                    map.put("group_BotPermission","普通成员");//在这个群里的权限
            }
            list.add(map);
        }
        return new Table_Json(0,null,new Long(groups.size()),list);
    }
    /**
     * Q群监控功能配置管理
     * @param qq
     */
    @PostMapping("/UpdateBotGroupsQQ")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    @ApiOperation(value = "Q群监控功能配置管理", notes = "Q群监控功能配置管理--拦截")
    public String UpdateBotGroupsQQ(String qq,String group,String task,boolean state){
        String index = state?"0":"1";
        if(botgroupsService.UpdateBotGroupsQQ(qq,group,task,index,null)){
            return "1";
        }else {
            return "0";
        }
    }
}
